<?php

namespace app\crm\controller;


use app\crm\model\Help;
use think\Request;
use think\Validate;

class Sys extends BaseController
{
    public function set()
    {
        return $this->fetch();
    }

    public function getList(Request $request)
    {
        $helpType = config('help.help_type');
        $page = $request->get('page', 1);
        $pageSize = $request->get('pageSize', 10);
        $where = [];
        $lists = Help::pagination($where, $pageSize);
        $page = $lists->render();
        $lists = $lists->toArray();
        $lists = $lists['data'];
        foreach ($lists as $k => $v) {
            foreach ($helpType as $k2 => $v2) {
                if ($v['type'] == $k2) {
                    $lists[$k]['type'] = $v2;
                }
            }
        }
        $this->assign('type', json_encode($helpType));
        $this->assign('list', $lists);
        $this->assign('page', $page);
        return $this->fetch('help');
    }

    public function insert(Request $request)
    {
        $data = [];
        $data['title'] = $request->post('title', '');
        $data['type'] = $request->post('type', 1);
        $data['content'] = $request->post('content', '');
        $data['end_active_time'] = $request->post('date', '');
        $data['order'] = $request->post('order_id', 1);

        $validate = new Validate([
            'title' => 'require',
            'type' => 'require',
            'content' => 'require',
            'end_active_time' => 'require',
            'order' => 'require|number'
        ]);

        if (!$validate->check($data)) {
            return json(['code' => 0, 'msg' => $validate->getError()]);
        }
        $data['add_time'] = time();
        $res = Help::insert($data);
        $output = $res ? ['code' => 1, 'msg' => '添加成功'] : ['code' => 0, 'msg' => '添加失败'];
        return json($output);
    }

    public function delHelp(Request $request)
    {
        $id = $request->post('id', '');
        if ($id <= 0) {
            return json(['code' => 0, 'msg' => 'id格式不正确']);
        }
        $info = Help::one(['id' => $id]);
        if (!$info) {
            return json(['code' => 0, 'msg' => '没有记录']);
        }
        $res = Help::del(['id' => $id]);
        $output = $res ? ['code' => 1, 'msg' => '删除成功'] : ['code' => 0, 'msg' => '删除失败,请重试'];
        return json($output);
    }
}